<template>
  <a-form
    ref="formRef"
    :model="storeData.data"
    class="form"
    :label-col-props="{ span: 8 }"
    :wrapper-col-props="{ span: 16 }"
    layout="horizontal"
    auto-label-width
  >
    <a-form-item field="storeName" label="店铺名称">
      <a-input v-model="storeData.data.storeName" disabled />
    </a-form-item>
    <a-form-item field="storeLogo" label="店铺logo">
      <!--<a-upload list-type="picture-card" action="/" :file-list="storeData.data.storeLogo ? storeData.storeLogo : []" image-preview/>-->
      <a-space v-for="(item, index) in storeData.storeLogo" :key="index">
        <a-image
          style="margin: 0 5px 5px 0"
          width="120"
          height="120"
          :src="item"
        >
        </a-image>
      </a-space>
      <div style="display: flex; justify-content: flex-start">
        <a-button @click="handleClickOssManages('storeLogo')" type="primary"
          >上传图片</a-button
        >
      </div>
    </a-form-item>
    <a-form-item field="storeAddressIdPath" label="店铺地址">
      <city
        :key="isShowCity"
        :ids="storeData.data.storeAddressIdPath"
        :address="storeData.data.storeAddressPath"
        @callback="cityRes"
      />
    </a-form-item>
    <a-form-item field="storeAddressDetail" label="详细地址">
      <a-textarea
        v-model="storeData.data.storeAddressDetail"
        :max-length="500"
        show-word-limit
        allow-clear
      />
    </a-form-item>

    <a-form-item field="storeDesc" label="店铺简介">
      <a-textarea
        v-model="storeData.data.storeDesc"
        :max-length="500"
        show-word-limit
        allow-clear
      />
    </a-form-item>
    <a-form-item field="stockWarning" label="库存预警" row-class="keep-margin">
      <a-input-number
        v-model="storeData.data.stockWarning"
        :min="0"
        :max="99999"
      />
    </a-form-item>
    <a-form-item field="pageShow" label="店铺楼层">
      <a-switch v-model="storeData.data.pageShow" />
    </a-form-item>

    <a-form-item field="selfPickFlag" label="开启自提">
      <a-switch v-model="storeData.data.selfPickFlag" />
    </a-form-item>

    <a-form-item label="操作">
      <a-button :loading="loading" type="primary" @click="submitStoreInfo">
        保存
      </a-button>
    </a-form-item>

    <!--上传图片弹框-->
    <a-modal
      v-model:visible="showOssManages"
      :width="966"
      title="选择图片"
      :body-style="{ paddingTop: '0px', paddingBottom: '0px' }"
      @ok="ossManagesOk"
      @cancel="showOssManages = false"
    >
      <ossManages
        :initialize="showOssManages"
        @selected="ossManagesSelected"
      ></ossManages>
    </a-modal>
  </a-form>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { getStoreInfo, setStoreInfo } from '@/api/login';
  import { setMerchantId, setStockWarning } from '@/api/shops';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import city from '@/components/m-city/index.vue';
  import { useUserStore } from '@/store';
  import { useRouter } from 'vue-router';
  import ossManages from '@/components/oss-manages/index.vue';
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  const message = useCurrentInstance().globalProperties?.$message;
  const loading = ref<boolean>(false);
  let defaultData: any;
  const isShowCity = ref(1);
  const storeData = reactive<any>({
    data: {
      storeAddressPath: '',
      storeName: '',
      merchantEuid: '',
      countryRegion: '',
      stockWarning: 0,
      storeDesc: '',
      storeAddressDetail: '',
      storeLogo: '',
      pageShow: false,
      selfPickFlag: false,
    },
    storeLogo: [], // 店铺Logo
  });

  const showOssManages = ref(false); // 上传图片弹框
  const ossManagesType = ref(); // 上传图片类型 goods商品图片，sku商品规格图片
  const ossManagesList = ref([]);
  // 点击上传图片按钮
  const handleClickOssManages = (type: any) => {
    showOssManages.value = true;
    ossManagesType.value = type;
  };
  // 从子组件获取选择的图片
  const ossManagesSelected = (value: any) => {
    ossManagesList.value = value;
  };
  // 上传图片弹框确认
  const ossManagesOk = () => {
    showOssManages.value = false;
    if (ossManagesType.value === 'storeLogo' && ossManagesList.value.length) {
      if (ossManagesList.value && ossManagesList.value.length === 1) {
        storeData.storeLogo = [];
        ossManagesList.value.forEach((item: any) => {
          storeData.storeLogo.push(item.url);
        });
      } else {
        Message.warning('只能上传一张图片！');
      }
    }
  };
  // 移除图片
  const handleRemoveIntro = (index: number | string, type: string) => {
    if (type === 'storeLogo') {
      storeData.data.value.images.splice(index, 1);
    } else {
      storeData.value[type].splice(index, 1);
    }
  };

  /**
   * 获取店铺详情
   */
  async function getStoreData() {
    const res = await getStoreInfo();
    console.log('获取店铺详情', res);
    isShowCity.value += 1;
    storeData.data = res.data.result;
    defaultData = JSON.parse(JSON.stringify(res.data.result));
    if (res.data.result && res.data.result.storeLogo) {
      storeData.storeLogo.push(res.data.result.storeLogo); // Logo
    }
  }

  /**
   * 提交修改店铺
   * 遍历出更改的值然后将值进行更改
   */
  async function submitStoreInfo() {
    loading.value = true;
    // 保存差异的内容
    const diff: any = {};
    Object.keys(defaultData).forEach((key) => {
      if (defaultData[key] != storeData.data[key]) {
        diff[key] = storeData.data[key];
      }
    });
    storeData.data.storeLogo =
      storeData.storeLogo && storeData.storeLogo.length
        ? storeData.storeLogo[0]
        : '';
    // 将差异的内容根据接口进行修改
    Promise.all([
      diff.merchantEuid
        ? (await setMerchantId({ merchantEuid: diff.merchantEuid })) &&
          delete diff.merchantEuid
        : '', // 修改客服
      diff.stockWarning
        ? (await setStockWarning({ stockWarning: diff.stockWarning })) &&
          delete diff.stockWarning
        : '', // 修改库存预警
      setStoreInfo(storeData.data), // 修改基本信息
    ]).then((res) => {
      if (
        res.some((item) => {
          return item;
        })
      ) {
        getInfo();
        message.success('保存成功');
      }
    });
    loading.value = false;
  }

  // 级联子组件传过来的值
  const cityRes = (val: any) => {
    storeData.data.storeAddressIdPath = val.ids.join(',');
    storeData.data.storeAddressPath = val.cities.join(',');
  };

  async function getInfo() {
    const store = useUserStore();
    const storeInfo = await getStoreInfo();
    store.userInfo = storeInfo.data.result;
    router.go(0);
  }

  // 加载方法
  onMounted(() => {
    getStoreData();
  });
</script>

<style scoped lang="less">
  .form {
    width: 590px;
    /*margin: 0 auto;*/
  }
  .actions {
    display: flex;
    align-items: center;
    margin-left: 70px;
    .action {
      padding: 5px 4px;
      font-size: 14px;
      // margin-left: 12px;
      border-radius: 2px;
      line-height: 1;
      cursor: pointer;
    }
  }
</style>
